package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.BehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author DiXiaoNie
 * @since 2023/1/3 16:39
 */
@Service
public class BehaviorServiceImpl implements BehaviorService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 加载行为
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/03
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.参数校验
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取用户登录ID
        ApUser apUser = ApThreadLocalUtil.getApUserThreadLocal();
        //判断是是否是游客登录
        if (apUser == null || apUser.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //定义默认变量
        Boolean islike = false, isunlike = false, iscollection = false, isfollow = false;

        //3.根据条件从redis中去查询
        // 是否关注过
        String followKey = "USER_FOLLOW_" + apUser.getId();
        Boolean followFlag = this.redisTemplate.opsForHash().hasKey(followKey,  dto.getAuthorId().toString());
        if (followFlag) {
            isfollow = true;
        }
        // 是否点赞过
        String likeKey = "USER_LIKE_" + dto.getArticleId();
        Boolean likeFlag = this.redisTemplate.opsForHash().hasKey(likeKey, apUser.getId().toString());
        if (likeFlag) {
            islike = true;
        }
        // 是否不喜欢过
        String unLikeKey = "USER_UNLIKE_" + dto.getArticleId();
        Boolean unLikeFlag = this.redisTemplate.opsForHash().hasKey(unLikeKey, apUser.getId().toString());
        if (unLikeFlag) {
            isunlike = true;
        }
        // 是否收藏过
        String collectionKey = "USER_COLLECTION_" + dto.getArticleId();
        Boolean collectionFlag = this.redisTemplate.opsForHash().hasKey(collectionKey, apUser.getId().toString());
        if (collectionFlag) {
            iscollection = true;
        }
        Map resultMap = new HashMap();
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("isfollow", isfollow);
        resultMap.put("iscollection", iscollection);
        return ResponseResult.okResult(resultMap);
    }
}
